package com.market.member.service.verify;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.service.LogFactory;
import com.market.member.config.LocaVerifyConfig;
import com.market.member.model.dto.LocalVerifyDTO;
import com.market.member.model.result.LocalVerifyResult;
import com.market.member.service.ILocalVerifyService;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 网易易盾 本机验证
 */
@Service
public class WangYiLocalVerifyServiceImpl implements ILocalVerifyService {

    private static Logger log = LogFactory.getCommLog();

    @Autowired
    LocaVerifyConfig locaVerifyConfig;

    private static List<String> successCodeList = Arrays.asList("0", "100", "103000");

    @Override
    public LocalVerifyResult verifyUserMobileInfo(LocalVerifyDTO localVerifyDTO){

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("secretId", locaVerifyConfig.getSecretId());
        paramMap.put("businessId", locaVerifyConfig.getBusinessId());
        paramMap.put("version", "v1");
        paramMap.put("timestamp", String.valueOf(System.currentTimeMillis()));
        paramMap.put("nonce", RandomUtil.randomString(32));
        paramMap.put("token", localVerifyDTO.getLoginToken());
        paramMap.put("accessToken", localVerifyDTO.getAccessToken());

        String sign = this.genSignature(locaVerifyConfig.getSecretKey(), paramMap);
        paramMap.put("signature", sign);

        String requestUrl = locaVerifyConfig.getHostUrl();
        log.info("【网易易盾】【本机校验】开始请求【requestUrl】{}【paramMap】{}", requestUrl, JSON.toJSONString(paramMap));
        HttpRequest httpRequest = HttpUtil.createPost(requestUrl);
        httpRequest.form(paramMap);
        String response = httpRequest.execute().body();
        log.info("【网易易盾】【本机校验】请求结束【response】{}", response);

        JSONObject resultObject = JSON.parseObject(response);

        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");
        JSONObject data = resultObject.getJSONObject("data");

        LocalVerifyResult verifyResult = new LocalVerifyResult();
        verifyResult.setSuccess(false);
        verifyResult.setRespCode(String.valueOf(code));
        verifyResult.setRespMsg(msg);
        verifyResult.setRespData(response);
        if (StrUtil.equals("200", String.valueOf(code))){
            // 请求成功
            String  phone = data.getString("phone");
            String  resultCode = data.getString("resultCode");
            if (successCodeList.contains(resultCode)){
                verifyResult.setSuccess(true);
                verifyResult.setMobile(phone);
            }
        }
        return verifyResult;
    }

    /**
     * 生成签名信息
     * @param secretKey 产品私钥
     * @param params 接口请求参数名和参数值map，不包括signature参数名
     * @return
     */
    public String genSignature(String secretKey, Map<String, Object> params){
        // 1. 参数名按照ASCII码表升序排序
        String[] keys = params.keySet().toArray(new String[0]);
        Arrays.sort(keys);

        // 2. 按照排序拼接参数名与参数值
        StringBuilder sb = new StringBuilder();
        for (String key : keys) {
            sb.append(key).append(params.get(key));
        }
        // 3. 将secretKey拼接到最后
        sb.append(secretKey);

        // 4. MD5是128位长度的摘要算法，转换为十六进制之后长度为32字符
        return DigestUtils.md5Hex(sb.toString().getBytes());
    }
}
